package transaction.xml;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public int getBookPriceById(int id) {
		String sql = "SELECT price FROM book WHERE id = ?";
		return jdbcTemplate.queryForObject(sql, Integer.class, id);
	}

	@Override
	public void updateBookStock(int id) {
		String checkSql = "SELECT stock FROM book_stock WHERE id = ?";
		int stock = jdbcTemplate.queryForObject(checkSql, Integer.class, id);
		if(stock == 0){
			throw new BookStockException("Low Stock");
		}
		String sql = "UPDATE book_stock SET stock = stock-1 WHERE id = ? ";
		jdbcTemplate.update(sql, id);
	}

	@Override
	public void updateUserAccount(int userId, int cost) {
		String checkSql = "SELECT balance FROM account WHERE id = ?";
		int balance = jdbcTemplate.queryForObject(checkSql, Integer.class, userId);
		if(balance < cost){
			throw new UserAccountException("Low Account");
		}
		String sql = "UPDATE account set balance = balance - ? WHERE id = ?";
		jdbcTemplate.update(sql, cost, userId);
	}
}
